var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();

const Upyun = require('../../utils/upyun-wxapp-sdk');
const upyun = new Upyun({
  bucket: util.upyun_bucket,
  operator: util.upyun_opterator,
  getSignatureUrl: util.upyun_getSignUrl
})

Page({
  data: {
    util: util,
    tc: 0,

    isIphone_x: false,
    nav_bgColor: '#ffffff',
    
    token: '',
    uid: 0,
    userInfo:{},
    isShow: false,
    user_jifen: 0,
    tx:"",

    edit_type: 1,

    areaArr: '',
    areaIndex: 0,
    areaSelected: '',


    phone:'',//手机号
    code:'',//验证码
    codename:'获取验证码'
  },

  user_Info: '',

  onLoad: function(data){
    var that = this;
    let editType = data.edittype;
    var tc = app.get_tc();//简体繁体转换
    console.log("tc======",tc);
    that.setData({
      tc: tc,
      edit_type: editType
    });
    this.getLoginInfo();
    var titleName = '更改姓名';
    if(editType == 2){
      titleName = tc == 1 ? '更改電話' : '更改电话';
    } else if(editType == 3) {
      titleName = '更改地址';
    }else if(editType == 4) {
      titleName = tc == 1 ? '修改密碼' : '修改密码';
    }
    wx.setNavigationBarTitle({
      title: titleName,
    })

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });


    wx.getSystemInfo({
      success: function(res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
        });
      }
    });

    // //获取关于等信息
    // app.getAllAbout('contact', function (res) {
    //   that.setData({
    //     contact_phone: res
    //   })
    // });

  },

  onShow:function(){
    
  },

  getLoginInfo: function(){
    var that = this;
    app.getLoginUserInfo(function (res) {
      console.log("mine login:", res);
      res.address1 = '';
      res.address2 = '';
      res.address3 = '';
      that.setData({
        uid: res.uid,
        token: res.token,
        userInfo: res,
        phone:res.phone.substring(0, 3) + '****' + res.phone.substring(res.phone.length-4,res.phone.length),
        
      });
      that.user_Info = res;
      if (that.data.edit_type == 3) {
        that.getYunfeiSet();
      }

    });
  },


  goAtherPage: function(e){
    console.log("goAtherPage",e)
      var url = e.currentTarget.dataset.link;
      wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function(e){
      var url = e.currentTarget.dataset.link;
      wx.redirectTo({url: url})
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      path = path.slice(6);
    }
    if (path) {
      wx.reLaunch({
        url: path,
      })
    }
  },

  //页面分享
  onShareAppMessage: function () {
    var invUid = this.data.uid ? this.data.uid : '';

    var path = '/pages/mine/mine?inviteuid=' + invUid;
    console.log("分享给好友：" + path);
     if (util.orgid == "21398") {
      return {
        title: this.data.tc == 1 ? '尚品高質凍肉海產零售批發小程序開通啦，歡迎下單購買！！！':'尚品高质冻肉海产零售批发小程序开通啦，欢迎下单购买！！！',
        path: path
      };
    } else{
      return {
        title: '',
        path: path
      };
    }
    
  },


  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    });
    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  nameEdited: function (e) {
    this.user_Info.uname = e.detail.value;
  },

  phoneEdited: function (e) {
    this.user_Info.phone = e.detail.value;
  },

  //获取运费设置
  getYunfeiSet: function () {
    wx.showLoading({
      title: 'loading',
    });
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "xsdyunfei",
        "binduid": util.orgid
      },
      success: function (responseData) {
        wx.hideLoading();
        console.log("运费：", responseData);
        var data = responseData.data;
        if (data.res == undefined) {
          that.setData({
            areaArr: data,
            areaSelected: data[0]
          })
          let u_info = that.user_Info;
          u_info.address1 = data[0].area;
          that.user_Info.address = u_info.address1 + u_info.address2 + u_info.address3; 
        }
        
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //区域切换
  areaPicker: function (e) {
    let index = e.detail.value;
    let sel = this.data.areaArr[index];
    this.setData({
      areaIndex: index,
      areaSelected: sel
    });
    let u_info = this.user_Info;
    u_info.address1 = sel.area;
    this.user_Info.address = u_info.address1 + u_info.address2 + u_info.address3; 
  },
  addressEdited1: function (e) {
    let u_info = this.user_Info;
    u_info.address1 = e.detail.value;
    this.user_Info.address = u_info.address1 + u_info.address2 + u_info.address3; 
  },
  addressEdited2: function (e) {
    let u_info = this.user_Info;
    u_info.address2 = e.detail.value;
    this.user_Info.address = u_info.address1 + u_info.address2 + u_info.address3; 
  },
  addressEdited3: function (e) {
    let u_info = this.user_Info;
    u_info.address3 = e.detail.value;
    this.user_Info.address = u_info.address1 + u_info.address2 + u_info.address3; 
  },

  pwdEdited1: function (e) {
    this.setData({
      oldpassword:e.detail.value
    })
  },
  pwdEdited2: function (e) {
    this.setData({
      newpassword:e.detail.value
    })
  },

  saveCard: function(){
    var that = this;
    

    if (this.data.edit_type == 4){
      if (!this.data.oldpassword || this.data.oldpassword.trim().length <= 0) {
        wx.showToast({
          title: that.data.tc == 1 ? '請輸入原密碼' : '请输入原密码',
          icon: 'none',
          image:'/images/gth.png'
        })
        return;
      }

      if (!this.data.newpassword || this.data.newpassword.trim().length <= 0) {
        wx.showToast({
          title: that.data.tc == 1 ? '請輸入新密碼' : '请输入新密码',
          icon: 'none',
          image:'/images/gth.png'
        })
        return;
      }

      wx.showLoading({
      title: '',
      mask:true
    })
    
    console.log("id",that.data.uid);
    console.log("token",that.data.token);
    var privatekey = utilMd5.hexMD5(that.data.uid + "checkaomensms" + that.data.token);
    var data = {
      "publickey": util.publiccode,
      "ac": "checkaomensms",
      "uid": that.data.uid,
      "privatekey": privatekey,
      "phone": that.user_Info.phone,
      "code": that.data.code,
    };
    
  
      util.actionSMS({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var resData = responseData.data;
        console.log(resData);
        if(resData.res == true){

          var tmpmd5 = utilMd5.hexMD5(that.data.uid + "bindhuiyuan" + that.data.token);
    
          var params = {
            "publickey": util.publiccode,
            "privatekey": tmpmd5,
            "ac": "bindhuiyuan",
            "uid": that.data.userInfo.uid,
            "realname": that.user_Info.uname,
            "mobile": that.user_Info.phone,
            "phone": that.user_Info.phone,
            "address": that.user_Info.address,
            "password": that.data.newpassword,
            "oldpassword":that.data.oldpassword,
      
          };
          console.log("编辑资料params：", params);
          util.api({
            data: params,
            method: "POST",
            success: function (responseData) {
              console.log(responseData);
              wx.hideLoading();
              if(responseData.data.res){
                app.dialogToast("編輯成功", "success", function(){
                  wx.navigateBack({
                    delta:1
                  })
                });
              } else {
                wx.showToast({
                  title: responseData.data.msg,
                })
              }
            }
          });

         }else{
           wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: resData.msg,
            showCancel: false,
          })
          
        } 
      }
    });
      
    }else{
      if (!this.user_Info.uname || this.user_Info.uname.trim().length <= 0){
        wx.showToast({
          title: that.data.tc == 1 ? '請輸入姓名' : '请输入姓名',
          icon:'none',
          image:'/images/gth.png'
        })
        return;
      }
      if (!this.user_Info.phone || this.user_Info.phone.trim().length <= 0) {
        wx.showToast({
          title: that.data.tc == 1 ? '請輸入電話號碼' : '请输入电话号码',
          icon: 'none',
          image:'/images/gth.png'
        })
        return;
      }
      if (this.data.edit_type == 3){
        if (!this.user_Info.address1 || this.user_Info.address1.trim().length <= 0) {
          wx.showToast({
            title: that.data.tc == 1 ? '請輸入地區' : '请输入地区',
            icon: 'none',
            image:'/images/gth.png'
          })
          return;
        }
        if (!this.user_Info.address2 || this.user_Info.address2.trim().length <= 0) {
          wx.showToast({
            title: that.data.tc == 1 ? '請輸入道路' : '请输入道路',
            icon: 'none',
            image:'/images/gth.png'
          })
          return;
        }
        if (!this.user_Info.address3 || this.user_Info.address3.trim().length <= 0) {
          wx.showToast({
            title: that.data.tc == 1 ? '請輸入大廈名' : '请输入大厦名',
            icon: 'none',
            image:'/images/gth.png'
          })
          return;
        }

      }

       var tmpmd5 = utilMd5.hexMD5(that.data.uid + "usercominfo" + that.data.token);
 
        var params = {
          "privatekey": tmpmd5,
          "ac": "usercominfo",
          "uid": that.data.userInfo.uid,
          "edituid": that.data.userInfo.uid,
          "realname": that.user_Info.uname,
          "phone": that.user_Info.phone,
          "mobile": that.user_Info.phone,
          "address": that.user_Info.address,
          "avatar": that.data.tx,
    
        };
        console.log("编辑资料params：", params);
        util.api({
          data: params,
          method: "POST",
          success: function (responseData) {
            console.log(responseData);
            wx.hideLoading();
            if(responseData.data.res){
              app.dialogToast("編輯成功", "success", function(){
                wx.navigateBack({
                  delta:1
                })
              });
              that.saveAddress();
            } else {
              wx.showToast({
                title: responseData.data.msg,
              })
            }
          }
        });
    }

    

  },

  saveAddress: function () {
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + "addaddress" + that.data.token);
    util.api({
      data: {
        "privatekey": privatekey,
        "ac": "addaddress",
        "uid": that.data.userInfo.uid,
        "name": that.user_Info.uname,
        "phone": that.user_Info.phone,
        "address": that.user_Info.address,
        "psd_phone": '',
        "default": 1
      },
      method: "POST",
      success: function (responseData) {
        console.log("保存地址成功");
      }
    });
  },


  getCodeValue: function (e) {
    this.setData({
      code: e.detail.value
    })
  },

  getCode:function(){
    var that = this;
    var phone = that.user_Info.phone;

      that.setData({
        disabled: true
      })
      var privatekey = utilMd5.hexMD5(that.data.uid + "sendaomensms" + that.data.token);
    util.actionSMS({
        data: {
          "privatekey": privatekey,
          "ac": "sendaomensms",
          "uid": that.data.uid,
          "phone": phone,
        },
        method: "POST",
        success: function (responseData) {
          console.log(responseData)
          var resData = responseData.data;
          if(resData.res == true){
            wx.showToast({
              title: that.data.tc == 1 ? '短信發送成功' : '短信发送成功',
              icon: 'success',
              duration: 1000
            })

            var num = 61;
            var timer = setInterval(function () {
              num--;
              if (num <= 0) {
                clearInterval(timer);
                that.setData({
                  codename: '重新发送',
                  disabled: false
                })
  
              } else {
                that.setData({
                  codename: num + "s"
                })
              }
            }, 1000)
          }else{
            wx.showModal({
              title: '提示',
              content: resData.msg,
              showCancel: false,
            })
          }
          
        }
      })
    
    
  },

})